package com.sbs.gaoxinqutoilet.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.ListPopupWindow;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.lvfq.pickerview.TimePickerView;
import com.sbs.gaoxinqutoilet.R;
import com.sbs.gaoxinqutoilet.base.BaseBackFragment;
import com.sbs.gaoxinqutoilet.entity.AcceptImageEntity;
import com.sbs.gaoxinqutoilet.entity.FIleEditSaveUpEntity;
import com.sbs.gaoxinqutoilet.entity.MessageEvent;
import com.sbs.gaoxinqutoilet.entity.ShiGoInfoEntity;
import com.sbs.gaoxinqutoilet.entity.ShigoinfoDetialEntity;
import com.sbs.gaoxinqutoilet.entity.UploadImageEntity;
import com.sbs.gaoxinqutoilet.eventbus.EventCenter;
import com.sbs.gaoxinqutoilet.eventbus.StartNewFragmentEvent;
import com.sbs.gaoxinqutoilet.http.HttpApis;
import com.sbs.gaoxinqutoilet.http.Request;
import com.sbs.gaoxinqutoilet.interfaces.Constants;
import com.sbs.gaoxinqutoilet.interfaces.EventConstant;
import com.sbs.gaoxinqutoilet.interfaces.PopuClickListener;
import com.sbs.gaoxinqutoilet.myapp.MyApplication;
import com.sbs.gaoxinqutoilet.utils.GsonTools;
import com.sbs.gaoxinqutoilet.utils.HttpUtils;
import com.sbs.gaoxinqutoilet.utils.ImageLoaderUtils;
import com.sbs.gaoxinqutoilet.utils.ImageUtils;
import com.sbs.gaoxinqutoilet.utils.JsonUtil;
import com.sbs.gaoxinqutoilet.utils.LogUtils;
import com.sbs.gaoxinqutoilet.utils.NetTimeUtils;
import com.sbs.gaoxinqutoilet.utils.SPUtil;
import com.sbs.gaoxinqutoilet.utils.TimeUtils;
import com.sbs.gaoxinqutoilet.utils.UtilPop;
import com.sbs.gaoxinqutoilet.utils.appinstallerutils.ConstUtils;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.iwf.photopicker.PhotoPicker;
import top.zibin.luban.Luban;


/**
 * Created by 聪明一只哈 on 2018/6/1.
 * Time: 2018/6/1  10:01
 */

public class ToiletShiGoInfoDetialFragment extends BaseBackFragment implements View.OnClickListener {

    //假数据,传过来的值  存储在Bundle中
    private static final String ACCEPTdATA = "acceptdatabean";

    private static final int LAYOUT_ONE = 0;
    private static final int LAYOUT_TWO = 1;
    private static final int LAYOUT_THREE = 2;
    private static final int RESAULTCODESHOW = 360;

    private View view;

    private Toolbar toolbar;
    private ScrollView applyBuySv;
    private ImageView toolbarBack;
    private TextView toolbarTitle;

    //验收结果
    private ListPopupWindow accept_resault_popupWindow;
    List<String> accept_resaultlist = new ArrayList<>();

    private TimePickerView pvTime;

    //存储参数的集合
    private Map<String, String> qrbparams = new HashMap<>();
    //传过来的数据
    private ShiGoInfoEntity.DataBean acceptdatabean;
    private AcceptDetialRequest acceptDelrequest;
    private ArrayList<AcceptImageEntity> acceptImageEntities;

    private TextView upimg_statue;
    private RelativeLayout up_accept_rl_a;
    private RelativeLayout up_accept_rl_b;
    private ImageView sell_accept_one;
    private ImageView sell_accept_two;
    private ImageView image_accept_a;
    private ImageView image_accept_b;
    private ShigoinfoDetialEntity acceptDetialentity;
    private TextView tv_huming;
    private TextView tv_shigoinfo_type;
    private TextView tv_shigoinfo_year;
    private TextView tv_shigoinfo_huafei;
    private TextView tv_buildstyle;
    private TextView tv_shigoinfo_teamname;
    private TextView tv_shigoinfo_date;
    private Button bt_shigoinfo_save;
    private String optLevel;
    private String netTime;
    private String token_data;

    public static ToiletShiGoInfoDetialFragment newInstance(ShiGoInfoEntity.DataBean dataBean) {//AcceptItemEntity.DataBean

        Bundle args = new Bundle();
        args.putSerializable(ACCEPTdATA, dataBean);
        ToiletShiGoInfoDetialFragment fragment = new ToiletShiGoInfoDetialFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case LAYOUT_ONE:
                    loadLayoutOne();
                    break;
                case LAYOUT_TWO:
                    loadLayoutTwo();
                    break;
                case LAYOUT_THREE:
                    initView(view);
                    initListener();
                    loadMoreData();
                    break;
                default:

            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_shigoinfo_detial, container, false);
        View detialLl = view.findViewById(R.id.buy_apply_ll);

        detialLl.setFocusable(true);
        detialLl.setFocusableInTouchMode(true);
        detialLl.requestFocus();

        return view;
    }

    /**
     * 加载个人信息和问题列表 并初始化
     */
    private void loadLayoutOne() {
        ViewStub inflat_info = (ViewStub) view.findViewById(R.id.inflat_two);
        View inflat_two = inflat_info.inflate();
        tv_huming = (TextView) inflat_two.findViewById(R.id.tv_shigoinfo_huming);
        tv_shigoinfo_type = (TextView) inflat_two.findViewById(R.id.tv_shigoinfo_type);
        tv_shigoinfo_year = (TextView) inflat_two.findViewById(R.id.tv_shigoinfo_year);
        tv_shigoinfo_huafei = (TextView) inflat_two.findViewById(R.id.tv_shigoinfo_huafei);
        tv_buildstyle = (TextView) inflat_two.findViewById(R.id.tv_buildstyle);
        tv_shigoinfo_teamname = (TextView) inflat_two.findViewById(R.id.tv_shigoinfo_teamname);
        tv_shigoinfo_date = (TextView) inflat_two.findViewById(R.id.tv_shigoinfo_date);


    }

    /**
     * 加载余下的布局 并初始化
     */
    private void loadLayoutTwo() {

        //上传文件列表
        ViewStub inflat_up_image = (ViewStub) view.findViewById(R.id.inflat_up_image);
        View inflate_three = inflat_up_image.inflate();
        upimg_statue = (TextView) inflate_three.findViewById(R.id.tv_upimg_statue);
        up_accept_rl_a = (RelativeLayout) inflate_three.findViewById(R.id.up_accept_rl_a);
        up_accept_rl_b = (RelativeLayout) inflate_three.findViewById(R.id.up_accept_rl_b);
        sell_accept_one = (ImageView) inflate_three.findViewById(R.id.sell_accept_one);
        sell_accept_two = (ImageView) inflate_three.findViewById(R.id.sell_accept_two);
        image_accept_a = (ImageView) inflate_three.findViewById(R.id.image_accept_a);
        image_accept_b = (ImageView) inflate_three.findViewById(R.id.image_accept_b);
        bt_shigoinfo_save = (Button) inflate_three.findViewById(R.id.bt_shigoinfo_save);


    }

    /**
     * 动画结束后执行
     * 通过handler加载布局
     *
     * @param savedInstanceState
     */
    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        showLoadingDialog("正在加载....");


        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                handler.sendEmptyMessage(LAYOUT_ONE);
            }
        }, 200);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                handler.sendEmptyMessage(LAYOUT_TWO);
            }
        }, 600);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                handler.sendEmptyMessage(LAYOUT_THREE);
            }
        }, 1200);
    }

    /**
     * 初始化公用布局,如:toolbar  scrollview
     *
     * @param view
     */
    private void initView(View view) {
        EventBus.getDefault().register(this);

        token_data = SPUtil.getString(Constants.KEY_TOKEN, "");

        //toolbar初始化
        applyBuySv = (ScrollView) view.findViewById(R.id.my_jescrollview);
        toolbarBack = (ImageView) view.findViewById(R.id.toolbar_back);
        toolbarTitle = (TextView) view.findViewById(R.id.toolbar_title);
        toolbar = (Toolbar) view.findViewById(R.id.toolbar);
        toolbarTitle.setText("施工记录信息采集");
        //返回箭头
        toolbarBack.setVisibility(View.VISIBLE);
        //user的列表信息  页面初始化时隐藏
        //accept_user_showbody.setVisibility(View.GONE);
        //返回箭头功能 同步
        initToolbarBack(toolbar);


//=====================获取传递过来的值=====================================
        Bundle arguments = getArguments();
        if (arguments != null) {
            acceptdatabean = (ShiGoInfoEntity.DataBean) arguments.getSerializable(ACCEPTdATA);

            boolean edit = acceptdatabean.isEdit();
            LogUtils.i("跳转接受过来的数据", "initView: " + edit);
            optLevel = acceptdatabean.getLevel();

            //false,不可编辑  true 可编辑
            if (!edit) {
                // up_accept_rl_a.setEnabled(false);
                bt_shigoinfo_save.setEnabled(false);
                tv_shigoinfo_date.setEnabled(false);
                bt_shigoinfo_save.setBackgroundResource(R.drawable.toilet_sliding_tv_unselected);
            }
        }
//=======================================================================

        getNetTimeNow();
    }

    private void getNetTimeNow() {
        new Thread() {
            @Override
            public void run() {
                netTime = NetTimeUtils.getNetTime();
            }
        }.start();
    }

    /**
     * 添加的各种监听
     */
    private void initListener() {

        bt_shigoinfo_save.setOnClickListener(this);
        tv_shigoinfo_date.setOnClickListener(this);

        //上传图片
        up_accept_rl_a.setOnClickListener(this);
        up_accept_rl_b.setOnClickListener(this);


    }

    /**
     * 加载验收详情数据
     */
    private void loadMoreData() {
        //加载user信息

        if (acceptdatabean != null) {
            String accept_detial_url = HttpApis.buildinfodetial + acceptdatabean.getShgjilu_id();
            LogUtils.i("施工采集详情", "loadMoreData: " + accept_detial_url);
            if (acceptDelrequest == null) {
                acceptDelrequest = new AcceptDetialRequest();
            }
            HashMap<String, String> map = new HashMap<>();
            map.put("token",token_data);
            HttpUtils.requestGet(_mActivity, accept_detial_url,map, acceptDelrequest);

            record_list.clear();
            getAcceptImageData(acceptdatabean.getShgjilu_id());


        }

    }

    /**
     * 请求图片数据
     *
     * @param acceptid
     */
    private void getAcceptImageData(String acceptid) {

        final String accept_image_data = HttpApis.acceptDetial_image;//+acceptid

        LogUtils.i("验收图片数据", accept_image_data);
        Map<String, String> params = new TreeMap<>();
        params.put("mid", acceptid);
        params.put("token",token_data);
        HttpUtils.requestPost(_mActivity, accept_image_data, params, new Request() {
            @Override
            public void success(String jsonStr) {
                super.success(jsonStr);
                LogUtils.i("验收图片数据", jsonStr);

                Type type = new TypeToken<ArrayList<AcceptImageEntity>>() {
                }.getType();

                acceptImageEntities = JsonUtil.json2Collection(jsonStr, type);

                if (acceptImageEntities != null && acceptImageEntities.size() > 0) {
                    for (AcceptImageEntity acceptiamgedata : acceptImageEntities) {
                        processImageData(acceptiamgedata);
                    }

                }
                cancelLoadingDialog();
            }

            @Override
            public void error(String error) {
                super.error(error);
                LogUtils.i("验收图片数据", error);
                cancelLoadingDialog();
            }
        });
    }

    /**
     * 加载图片数据
     *
     * @param acceptiamgedata
     */
    private void processImageData(AcceptImageEntity acceptiamgedata) {
        switch (acceptiamgedata.getAdjunct_type()) {

            case "21":
                sell_accept_one.setVisibility(View.GONE);
                image_accept_a.setVisibility(View.VISIBLE);
                isRecordlistSuccess = true;
                up_accept_rl_a.setBackgroundColor(ContextCompat.getColor(_mActivity, R.color.color_translate));
                ImageLoaderUtils.setImageUrl(_mActivity, acceptiamgedata.getSys_file_name(), image_accept_a);

                recordlist_ima[0] = acceptiamgedata.getAdjunct_id();
                recordlist_ima[1] = acceptiamgedata.getSys_file_name();
                recordlist_ima[2] = "21";//adjunct_type : 据上传图片定
                recordlist_ima[3] = acceptiamgedata.getFile_type();
                recordlist_ima[4] = acceptiamgedata.getFile_size();
                //recordlist_ima[5] = "施工记录表";//file_des:据上传图片定 身份证正面\大门照
                recordlist_ima[5] = "改厕质量自检单";//file_des:据上传图片定 身份证正面\大门照
                recordlist_ima[6] = acceptiamgedata.getUser_file_name();
                recordlist_ima[7] = acceptiamgedata.getPicmd5code();

                record_list.add(acceptiamgedata);

                break;

            default:

                break;
        }

    }


    /**
     * 加载验收详情数据请求
     */
    private class AcceptDetialRequest extends Request {

        @Override
        public void success(String jsonStr) {
            super.success(jsonStr);
            LogUtils.i("施工采集详情", jsonStr);

            //处理修改的数据
            acceptDetialentity = GsonTools.changeGsonToBean(jsonStr, ShigoinfoDetialEntity.class);
            if (acceptDetialentity != null) {
                processModfiyData(acceptDetialentity);
                getAcceptImageData(acceptDetialentity.getGaizao_id());
            }
        }

        @Override
        public void error(String error) {
            super.error(error);
            LogUtils.i("施工采集详情", "error:" + error);
            cancelLoadingDialog();
        }
    }

    /**
     * 处理显示数据
     *
     * @param acceptDetialentity
     */
    private void processModfiyData(ShigoinfoDetialEntity acceptDetialentity) {


        tv_huming.setText(acceptDetialentity.getHuming());
        tv_shigoinfo_type.setText(acceptDetialentity.getGaizao_type_n());

        tv_shigoinfo_year.setText(acceptDetialentity.getStat_year_n());

        tv_shigoinfo_huafei.setText(acceptDetialentity.getHfc_material_n());
        tv_buildstyle.setText(acceptDetialentity.getGaizao_fangshi_n());
        tv_shigoinfo_teamname.setText(acceptDetialentity.getShgd_name());

        try {
            String shg_date = (String) acceptDetialentity.getShg_date_str();
            if (!TextUtils.isEmpty(shg_date)) {
                tv_shigoinfo_date.setText(shg_date);
                qrbparams.put("shg_date", shg_date);
            }
        } catch (Exception e) {
            Date date = new Date();

            try {
                date.setTime((long) acceptDetialentity.getShg_date());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String format = sdf.format(date);


                tv_shigoinfo_date.setText(format);
                qrbparams.put("shg_date", format);
            } catch (Exception ea) {
                Double shg_date = (Double) acceptDetialentity.getShg_date();
                long l = shg_date.longValue();
                date.setTime(l);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String format = sdf.format(date);


                tv_shigoinfo_date.setText(format);
                qrbparams.put("shg_date", format);
            }


        }

        //upimg_statue.setText("请上传《改厕质量自检单》");
        upimg_statue.setText("请上传《施工记录表》");


//        switch (acceptDetialentity.getGaizao_type_n()) {
//            case "三格式":
//                if ("砖砌".equals(acceptDetialentity.getHfc_material_n())) {
//                    upimg_statue.setText("请上传《砖砌三格式厕所改造施工记录表》");
//                } else if ("塑料合成".equals(acceptDetialentity.getHfc_material_n())
//                        || "玻璃钢".equals(acceptDetialentity.getHfc_material_n())
//                        || "其它".equals(acceptDetialentity.getHfc_material_n())
//                        || "其他".equals(acceptDetialentity.getHfc_material_n())) {
//                    upimg_statue.setText("请上传《一体三格式厕所改造施工记录表》");
//                }
//
//                break;
//            case "水冲式":
//                upimg_statue.setText("请上传《单坑加集中（水冲）式厕所改造施工记录表》");
//                break;
//            case "单坑加集中":
//            case "单坑+集中":
//                upimg_statue.setText("请上传《单坑加集中（水冲）式厕所改造施工记录》");
//                break;
//
//            default:
//
//                break;
//        }


    }

    /**
     * View的各种点击监听
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.bt_shigoinfo_save:
                if (getCheckParams()) {

                    //至此参数添加完成,上传参数上传完成后恢复为默认状态
                    syso(qrbparams);
                    showLoadingDialog();

                    SaveUpData();
                }

                break;


            case R.id.up_accept_rl_a:

                if ("302".equals(optLevel) || "301".equals(optLevel)) {
                    //GotoImageFgRecorelist(image_accept_a, "施工记录表");
                    GotoImageFgRecorelist(image_accept_a, "施工记录表","改厕质量自检单");
                } else {
                    mLayoutType = 4;
                    showPhotoPic();
                }


                break;
            case R.id.up_accept_rl_b:
//                mLayoutType = 5;
//                showPhotoPic();

                break;

            case R.id.tv_shigoinfo_date:
                TimePickerView.Type type = TimePickerView.Type.YEAR_MONTH_DAY;
                pvTime = new TimePickerView(_mActivity, type);
                String format = "yyyy-MM-dd";
                UtilPop.alertTimerPickerEh(getActivity(), pvTime, format, new UtilPop.TimerPickerCallBack() {
                    @Override
                    public void onTimeSelect(String date) {
                        String nowTime1 = getNowTime();
                        String nowTime = netTime;
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        TimeUtils.getIntervalTime2(date, nowTime, ConstUtils.TimeUnit.DAY, sdf);
                        if (TimeUtils.getTypeValue() == 1) {
                            if (date.equals(getNowTime())) {
                                if (!nowTime1.equals(netTime)) {
                                    showAlertOnlyPos(_mActivity, "施工日期", "该日期不能晚于今天" + netTime);
                                }
                            }else{
                                //showShortToast("选择时间不能晚于当前时间");
                                showAlertOnlyPos(_mActivity, "施工日期", "选择时间不能晚于当前时间"+netTime);
                            }
                            //showAlertOnlyPos(_mActivity, "施工日期", "选择时间不能晚于当前时间"+netTime);

                        } else {

                            if (date.equals(getNowTime())) {
                                if (!nowTime1.equals(netTime)) {
                                    showAlertOnlyPos(_mActivity, "施工日期", "该日期不能晚于今天" + netTime);
                                }else{
                                    tv_shigoinfo_date.setText(date);
                                }
                            }else{
                                tv_shigoinfo_date.setText(date);
                            }

                            //　选择时间　正确
                           // tv_shigoinfo_date.setText(date);
                            // qrbparams.put("shg_date_str", date);

                            //添加验收时间
                            //qrbparams.put("accept_date", date);
                        }
                    }
                });


                break;

            default:

                break;
        }
    }

    //记录表添加的数据
    private List<AcceptImageEntity> record_list = new ArrayList<>();

    private void GotoImageFgRecorelist(ImageView imageview, String contextValue) {

        if (imageview.getVisibility() == View.VISIBLE && record_list != null
                && record_list.size() > 0) {
            for (AcceptImageEntity acceptiamgedata : record_list) {
                if (contextValue.equals(acceptiamgedata.getFile_des())) {
                    EventBus.getDefault().post(new StartNewFragmentEvent(ImageShowFragment.newInstance(acceptiamgedata.getSys_file_name())));

                }
            }
        }

    }
    private void GotoImageFgRecorelist(ImageView imageview,String contextOldValue, String contextValue) {

        if (imageview.getVisibility() == View.VISIBLE && record_list != null
                && record_list.size() > 0) {
            for (AcceptImageEntity acceptiamgedata : record_list) {
                if (contextValue.equals(acceptiamgedata.getFile_des())||contextOldValue.equals(acceptiamgedata.getFile_des())) {
                    EventBus.getDefault().post(new StartNewFragmentEvent(ImageShowFragment.newInstance(acceptiamgedata.getSys_file_name())));

                }
            }
        }

    }

    private int mLayoutType = -1;

    private void showPhotoPic() {
        String carrier = android.os.Build.MANUFACTURER;
        LogUtils.i("手机厂商", "showPhotoPic: " + carrier);
        showPhotoPicker();
    }

    private void showPhotoPicker() {
        PhotoPicker.builder()
                .setPhotoCount(1) //显示图片张
                .setPreviewEnabled(false)
                .start(_mActivity, this, PhotoPicker.REQUEST_CODE);
    }

    /**
     * 获取的提交数据
     */
    private void SaveUpData() {

        String accept_up_save_url = HttpApis.buildinfoDetial_saveUp + acceptdatabean.getShgjilu_id();

        LogUtils.i("详情提交参数", "url: " + accept_up_save_url);

        qrbparams.put("idfield", "shgjilu_id");
        qrbparams.put("token",token_data);

        qrbparams.put("hasuptinfo", "1");//更改记录状态


        qrbparams.put("buchongfu", getBuChongfuTime());


        qrbparams.put("adjunct_id", recordlist_ima[0]);
        qrbparams.put("sys_file_name", recordlist_ima[1]);
        qrbparams.put("adjunct_type", recordlist_ima[2]);
        qrbparams.put("file_type", recordlist_ima[3]);
        qrbparams.put("file_size", recordlist_ima[4]);
        qrbparams.put("file_des", recordlist_ima[5]);
        qrbparams.put("user_file_name", recordlist_ima[6]);
        qrbparams.put("picmd5code", recordlist_ima[7]);


//        accept_up_save_url=accept_up_save_url +"?idfield=shgjilu_id"
//                +"&shg_date_str="+qrbparams.get("shg_date_str")
//                +"&shg_date="+Long.parseLong(qrbparams.get("shg_date"))
//                +"&buchongfu="+qrbparams.get("buchongfu")
//                +"&adjunct_id="+recordlist_ima[0]+"&adjunct_id="+recordlist_ima[0]
//                +"&sys_file_name="+recordlist_ima[1]+"&sys_file_name="+recordlist_ima[1]
//                +"&adjunct_type="+recordlist_ima[2]+"&adjunct_type="+recordlist_ima[2]
//                +"&file_type="+recordlist_ima[3]+"&file_type="+recordlist_ima[3]
//                +"&file_size="+recordlist_ima[4]+"&file_size="+recordlist_ima[4]
//                +"&file_des="+recordlist_ima[5]+"&file_des="+recordlist_ima[5]
//                +"&user_file_name="+recordlist_ima[6]+"&user_file_name="+recordlist_ima[6]
//
//        ;
//
//        LogUtils.i("详情提交参数", "url: " + accept_up_save_url);


//        HttpUtils.requestPostUrl(_mActivity, accept_up_save_url, new Request() {
//            @Override
//            public void success(String jsonStr) {
//                super.success(jsonStr);
//                LogUtils.i("详情提交参数", "success: " + jsonStr);
//                FIleEditSaveUpEntity fileeditip = GsonTools.changeGsonToBean(jsonStr, FIleEditSaveUpEntity.class);
//
//                if (fileeditip != null && "success".equals(fileeditip.getState())) {
//                    Toast.makeText(_mActivity, "上传成功!", Toast.LENGTH_SHORT).show();
//
//
//                    //提交完成后
//                    qrbparams.clear();
//
//                    EventBus.getDefault().post(new MessageEvent("360"));
//                    //保存成功后回到列表页
//                    _mActivity.onBackPressed();
//
//
//                }
//
//
//                cancelLoadingDialog();
//            }
//
//            @Override
//            public void error(String error) {
//                super.error(error);
//                LogUtils.i("详情提交参数", "error: " + error);
//                cancelLoadingDialog();
//            }
//        });
        HttpUtils.requestPost(_mActivity, accept_up_save_url, qrbparams, new Request() {
            @Override
            public void success(String jsonStr) {
                super.success(jsonStr);
                LogUtils.i("详情提交参数", "success: " + jsonStr);
                FIleEditSaveUpEntity fileeditip = GsonTools.changeGsonToBean(jsonStr, FIleEditSaveUpEntity.class);

                if (fileeditip != null && "success".equals(fileeditip.getState())) {
                    Toast.makeText(_mActivity, "上传成功!", Toast.LENGTH_SHORT).show();
                    //提交完成后
                    qrbparams.clear();
                    EventBus.getDefault().post(new MessageEvent("360"));
                    //保存成功后回到列表页
                    _mActivity.onBackPressed();
                }
                cancelLoadingDialog();
            }

            @Override
            public void error(String error) {
                super.error(error);
                LogUtils.i("详情提交参数", "error: " + error);
                cancelLoadingDialog();
            }
        });

    }

    private String getBuChongfuTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        return str;
    }

    /**
     * 提交数据前检查参数
     */
    private boolean getCheckParams() {

        if (!isRecordlistSuccess) {
            //showAlertOnlyPos(_mActivity, "照片", "请上传施工记录表照片");
            showAlertOnlyPos(_mActivity, "照片", "请上传施工记录表");
            return false;
        }

        String shigong_date = tv_shigoinfo_date.getText().toString().trim();
        if (TextUtils.isEmpty(shigong_date)) {
            showAlertOnlyPos(_mActivity, "施工日期", "请确认施工日期");
            return false;
        } else {

            if(shigong_date.contains(" ")){
                String[] s = shigong_date.split(" ");
                shigong_date=s[0];
            }

            qrbparams.put("shg_date", shigong_date);
        }


        return true;


    }

    /**
     * 页面回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE && data != null) {
                ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);

                //=========添加水印=========
                String absolutePath = photos.get(0);

                if (absolutePath.endsWith(":abc")) {
                    absolutePath = absolutePath.substring(0, absolutePath.length() - 4);
                    savePic(absolutePath);
                }


                //==========添加水印========

                showLoadingDialog("正在上传图片");
                for (int i = 0; i < photos.size(); i++) {
                    String uri = Uri.decode(photos.get(i));
                    if (uri.endsWith(":abc")) {
                        uri = uri.substring(0, uri.length() - 4);
                    }
                    LogUtils.e("uri", uri);
                    try {
                        compressWithRx(new File(uri));
                    } catch (Exception e) {
                        Toast.makeText(_mActivity, "请重新上传", Toast.LENGTH_SHORT).show();

                    }
                }

            }
        }
    }

    private void savePic(String filename) {

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPurgeable = true;
        options.inSampleSize = 2;
        Bitmap bm = BitmapFactory.decodeFile(filename, options);


        File file = new File(filename);

        // stringToBitmap(file.getAbsolutePath());
        try {
            FileOutputStream fos = new FileOutputStream(file);
//			FileInputStream fis = new FileInputStream(new File(tempPicPath)) ;
            byte[] temp = new byte[1024];
            //添加时间水印
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//            String time = sdf.format(new Date(System.currentTimeMillis()));

//            URL url = new URL("http://110.249.173.26:8081");
//            //url = new URL("http://www.baidu.com");
//            //url = new URL("http://www.ntsc.ac.cn");//中国科学院国家授时中心
//            //url = new URL("http://www.bjtime.cn");
//            URLConnection uc = url.openConnection();//生成连接对象
//            uc.connect(); //发出连接
//            long ld = uc.getDate(); //取得网站日期时间
//            Calendar calendar = Calendar.getInstance();
//            calendar.setTimeInMillis(ld);
//            int i = calendar.get(Calendar.YEAR);
//            int j = calendar.get(Calendar.MONTH);
//            j=j+1;
//            int x = calendar.get(Calendar.DAY_OF_MONTH);

            String time = netTime;

            String address = MyApplication.getAddress();
            if(address==null){
                address="";
            }

            Bitmap newbm = ImageUtils.drawTextToRightBottom(_mActivity, bm, time + ";" + address,
                    25, ContextCompat.getColor(_mActivity, R.color.show2), 10, 10);


            //Bitmap newbmOne = addTimeFlag(_mActivity,newbm);
            newbm.compress(Bitmap.CompressFormat.JPEG, 100, fos);// 把数据写入文件
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void compressWithRx(File file) {

        Flowable.just(file)
                .observeOn(Schedulers.io())
                .map(new Function<File, File>() {
                    @Override
                    public File apply(@NonNull File file) {//  throws Exception
                        try {
                            File file1 = Luban.with(_mActivity).load(file).get();
                            return file1;
                        } catch (Exception e) {
                            //对于文件损坏的文件/压缩失败的文件,也能上传,但是,在主线程中提示
                            //记住,修改权限
                            _mActivity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showShortToast("请重新上传");
                                }
                            });

                            return file;
                        }

                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<File>() {
                    @Override
                    public void accept(@NonNull File file) {
                        LogUtils.e("fileinfo", "file- " + file.length() / 1024 + "k" + " name- " + file.getName() + " paht- " + file.getPath());
                        //上传图片
                        if (file == null) {
                            Toast.makeText(_mActivity, "请重新上传", Toast.LENGTH_SHORT).show();
                        } else {
                            uploadImgFile(file, file.getName(), file.getPath());
                        }

                    }


                });
    }

    private boolean isUploadSuccess;

    private void uploadImgFile(final File file, final String fileName, final String filepath) {
        String url = HttpApis.upload_image;
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token_data);
        HttpUtils.requestPostFileMapUploades(getActivity(), url, fileName, file,map, new Request() {

            @Override
            public void success(String jsonStr) {
                super.success(jsonStr);
                LogUtils.i("上传图片成功detial", "jsonSuccess  " + jsonStr);
                UploadImageEntity uploadImageEntity = GsonTools.changeGsonToBean(jsonStr, UploadImageEntity.class);
                if ("SUCCESS".equals(uploadImageEntity.getState())) {

                    if ("0".equals(uploadImageEntity.getIsrepeat())) {
                        isUploadSuccess = true;
                        displayUploadImgFile(uploadImageEntity, fileName);  //将img显示
                    } else {
                        showAlertOnlyPos(_mActivity, "图片上传", "图片上传重复,请重新上传");
                        isUploadSuccess = false;
                    }


                } else {
                    //showShortToast("上传失败，图片大小不能超过4兆");
                    showAlertOnlyPos(_mActivity, "图片上传", "上传失败，图片大小不能超过4兆");
                    isUploadSuccess = false;
                }
                cancelLoadingDialog();
            }

            @Override
            public void error(String error) {
                super.error(error);
                isUploadSuccess = false;
                cancelLoadingDialog();
            }
        });

    }

    private String[] recordlist_ima = new String[]{null, null, null, null, null, null, null, null};
    private boolean isRecordlistSuccess;

    private void displayUploadImgFile(UploadImageEntity uploadImageEntity, String fileName) {

        qrbparams.put("adj_table_info","bill_adjunct$business_id");

        switch (mLayoutType) {
            case 4:

                sell_accept_one.setVisibility(View.GONE);
                image_accept_a.setVisibility(View.VISIBLE);
//                LogUtils.i("上传图片成功", "展示图片 1 " + uploadImageEntity.getFilePath());
                Glide.with(_mActivity).load(uploadImageEntity.getFilePath())
                        .into(image_accept_a);

                up_accept_rl_a.setBackgroundResource(R.color.status_translate);

                recordlist_ima[0] = uploadImageEntity.getFileID();
                recordlist_ima[1] = uploadImageEntity.getFilePath();
                recordlist_ima[2] = "21";//adjunct_type : 据上传图片定
                recordlist_ima[3] = uploadImageEntity.getFileExt();
                recordlist_ima[4] = uploadImageEntity.getSize();
                //recordlist_ima[5] = "施工记录表";//file_des:据上传图片定 身份证正面\大门照
                recordlist_ima[5] = "施工记录表";//file_des:据上传图片定 身份证正面\大门照
                recordlist_ima[6] = fileName;
                recordlist_ima[7] = uploadImageEntity.getPicmd5code();

                if (isUploadSuccess) {
                    isRecordlistSuccess = isUploadSuccess;
                }
                break;

            default:
                break;

        }

    }

    //模拟输出测验
    private void syso(Map<String, String> conditionmap) {
        Set<Map.Entry<String, String>> entrySet = conditionmap.entrySet();
        Iterator<Map.Entry<String, String>> iterator = entrySet.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> me = iterator.next();
            String key = me.getKey();
            String value = me.getValue();

            LogUtils.i("验收提交", key + ":" + value);

        }

    }


    /**
     * 得到当前时间
     */
    private String getNowTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        return str;
    }


    /**
     * 显示listpopuwindow,并使用回调,显示数据
     *
     * @param view
     * @param mPopupWindow
     * @param datalist
     */
    private void setPopuData(View view, final ListPopupWindow mPopupWindow, final List<String> datalist) {
        ArrayAdapter<String> adapter = new ArrayAdapter<>(_mActivity, android.R.layout.simple_list_item_1, datalist);
        mPopupWindow.setAdapter(adapter);

        //弹出的位置  弹出锚点
        mPopupWindow.setAnchorView(view);
        //设置宽高
        mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);

        mPopupWindow.setModal(true);//设置模态框，设置为true响应物理键
        //设置条目点击事件
        mPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //使用回调,显示数据
                if (popuClickListener != null) {
                    popuClickListener.show("" + datalist.get(position));
                }
                mPopupWindow.dismiss();
            }
        });
        mPopupWindow.show();
    }

    //-------------设置popu传值接口-----------------------------------------------------------
    public PopuClickListener popuClickListener;

    public void setPopuClickListener(PopuClickListener popuClickListener) {
        this.popuClickListener = popuClickListener;
    }

    /**
     * eventBus接受数据
     *
     * @param center
     */
    @Subscribe
    public void onEventThread(EventCenter center) {

        if (center.getEventCode() == EventConstant.ORG_SUPPLY_INFOR_INDEX) {


        }

    }


    @Override
    public void onPause() {
        super.onPause();
        if (pvTime != null && pvTime.isShowing()) {
            pvTime.dismiss();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (pvTime != null && pvTime.isShowing()) {
            pvTime.dismiss();
            pvTime = null;
        }
        //这里要不要释放这个map集合资源
        if (qrbparams != null) {

        }
        EventBus.getDefault().unregister(this);
        OkHttpUtils.getInstance().cancelTag(this);
        cancelLoadingDialog();
        handler.removeCallbacksAndMessages(null);
    }
}
